package org.vehicle.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.vehicle.entity.OrganizationInfo;
import org.vehicle.entity.security.MyUserDetail;
import org.vehicle.service.OrganizationInfoService;
import org.vehicle.service.VehicleInfoService;
import org.vehicle.service.redis.RedisService;
import org.vehicle.util.JsonUtils;

import com.fasterxml.jackson.databind.JsonNode;

@Controller
public class MapController {
	@Autowired
	private OrganizationInfoService organizationInfoService;
	@Autowired
	private VehicleInfoService vehicleInfoService;
	@Autowired
	private RedisService redisService;
	
	@RequestMapping("mapInfo")
	public String mapInfo(HttpServletRequest req, Model model){
		MyUserDetail ud = (MyUserDetail) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
		model.addAttribute("manager", ud);
		return "map";
	}
	
	@RequestMapping("getOrganizationList")
	@ResponseBody
	public Map<String, Object> getOrganizationList(HttpServletRequest req, Model model){
		Map<String, Object> map = new HashMap<String, Object>();
		List<OrganizationInfo> organizationInfoList=organizationInfoService.findCheckOrganizationInfoList();
		map.put("dataList", organizationInfoList);
		return map;
	}
	@RequestMapping("getRunVehicleList")
	@ResponseBody
	public Map<String, Object> getRunVehicleList(HttpServletRequest req, Model model){
		Map<String, Object> map = new HashMap<String, Object>();
		List<Map<String, Object>> vehicleInfoList=vehicleInfoService.findRunVehicleInfoList();
		List<Map<String, Object>> retMapList=new ArrayList<Map<String, Object>>();
		for(Map<String, Object> vehicleInfoMap:vehicleInfoList){
			String positionJson=redisService.getString((String)vehicleInfoMap.get("vehicleLicense"));
			if(!StringUtils.isEmpty(positionJson)){
				JsonNode positionJsonNode=JsonUtils.fromJson(positionJson);
				if(positionJsonNode.get("logitude")!=null){
					vehicleInfoMap.put("logitude", positionJsonNode.get("logitude").asText());
				}
				if(positionJsonNode.get("latitude")!=null){
					vehicleInfoMap.put("latitude", positionJsonNode.get("latitude").asText());
				}
				retMapList.add(vehicleInfoMap);
			}
		}
		map.put("dataList", vehicleInfoList);
		return map;
	}
}
